/*
 * Created on 2004-6-11 TODO To change the template for this generated file go
 * to Window - Preferences - Java - Code Generation - Code and Comments
 */

package cn.com.yinhex.as.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.DefaultHttpParams;
import org.apache.commons.httpclient.params.HttpClientParams;

/**
 * @author test TODO To change the template for this generated type comment go
 *         to Window - Preferences - Java - Code Generation - Code and Comments
 */
public class NetUtil {
	public static long connection_timeout = 10000;
	public static int so_timeout = 20000;

	static {
		init();
	}

	public static void init() {
		System.setProperty("apache.commons.httpclient.cookiespec", "COMPATIBILITY");
		DefaultHttpParams.getDefaultParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
	}

	/**
	 * ��ȡ��ҳ
	 * 
	 * @param urladdress
	 * @return
	 */
	public static String readURL(String urladdress) {
		return readURL(urladdress, "ISO-8859-1", "\n");
	}
	
	public static String readURL(String urladdress, String encoding)
	{
		return readURL(urladdress, encoding, "\n");
	}

	public static String readURL(String urladdress, String encoding, String splitor) {
		while (urladdress.indexOf("&amp;") > -1) {
			urladdress = StringUtil.replace(urladdress, "&amp;", "&");
		}
		urladdress = encodeUrl(urladdress);
		// ����GET������ʵ��
		GetMethod method = new GetMethod(urladdress);
		method.setFollowRedirects(true);
		// method.setRequestHeader("Accept-Encoding", "gzip, deflate");
		// method.setRequestHeader("X-Forwarded-For", "127.0.0.1");
		method.setRequestHeader("Accept-Language", "zh-cn");
		// method.setRequestHeader("Cookie", "pvid=1312542004");
		try {
			HttpClient client = new HttpClient();
			HttpClientParams cparams = new HttpClientParams();
			cparams.setConnectionManagerTimeout(connection_timeout);
			cparams.setSoTimeout(so_timeout);
			client.setParams(cparams);

			int statusCode = client.executeMethod(method);
			if (statusCode == 200) {

				InputStream is = method.getResponseBodyAsStream();
				InputStreamReader isr = new InputStreamReader(is, "ISO-8859-1");
				BufferedReader in = new BufferedReader(isr);
				String strread = null;

				StringBuffer buf = new StringBuffer();
				while ((strread = in.readLine()) != null) {
					buf.append(strread);
					buf.append(splitor);
				}
				in.close();
				is.close();
				isr.close();
				String str = buf.toString();
				if (StringUtil.isFine(encoding) && !encoding.equalsIgnoreCase("ISO-8859-1")) {
					return new String(str.getBytes("ISO-8859-1"), encoding);
				}
				return new String(str.getBytes("ISO-8859-1"), getCharset(str));
			}
			return "";
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		} finally {
			method.releaseConnection();
		}
	}

	public static String getCharset(String str) {
		Pattern p = Pattern.compile("<meta[^>]*>", 2);
		Matcher m = p.matcher(str);
		while (m.find()) {
			String meta = m.group(0).toLowerCase();
			if (meta.indexOf("http-equiv") > -1 && meta.indexOf("content-type") > -1 && meta.indexOf("content") > -1
					&& meta.indexOf("text/html") > -1) {
				Pattern p2 = Pattern.compile("<meta(.*?)charset=(.*?)['\" ]{1}[^>]*>");
				Matcher m2 = p2.matcher(meta);
				if (m2.find()) {
					String charset = m2.group(2);
					if (charset.equals("gb2312")) {
						return "GBK";
					}
					return charset.toUpperCase();
				}
			}
		}
		return "GBK";
	}

	/**
	 * �����ļ�
	 * 
	 * @param urladdress
	 * @param filename
	 * @return
	 */
	public static boolean download(String urladdress, String filename) {
		while (urladdress.indexOf("&amp;") > -1) {
			urladdress = StringUtil.replace(urladdress, "&amp;", "&");
		}
		try {
			downloadWithException(urladdress, filename, false);
			return true;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return false;
	}

	public static boolean download(String urladdress, String filename, boolean isunix) {
		try {
			downloadWithException(urladdress, filename, isunix);
			return true;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return false;
	}

	public static void downloadWithException(String urladdress, String filename, boolean isunix) throws Exception {
		urladdress = encodeUrl(urladdress);
		File file = new File(filename);
		file.getParentFile().mkdirs();
		// ����GET������ʵ��
		GetMethod method = new GetMethod(urladdress);
		method.setFollowRedirects(true);
		method.setRequestHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)");
		// method.setRequestHeader("Accept-Encoding", "gzip, deflate");
		method.setRequestHeader("X-Forwarded-For", "127.0.0.1");
		method.setRequestHeader("Referer", urladdress);
		try {
			HttpClient client = new HttpClient();
			HttpClientParams cparams = new HttpClientParams();
			cparams.setConnectionManagerTimeout(10000);
			cparams.setSoTimeout(15000);
			client.setParams(cparams);

			int statusCode = client.executeMethod(method);
			if (statusCode == 200) {
				BufferedInputStream istream = new BufferedInputStream(method.getResponseBodyAsStream());
				BufferedOutputStream ostream = new BufferedOutputStream(new FileOutputStream(file));
				byte[] bs = new byte[1];
				while ((istream.read(bs)) > -1) {
					ostream.write(bs);
				}
				ostream.close();
				istream.close();
			}
		} finally {
			method.releaseConnection();
		}
	}

	public static String getIP(String host) {
		try {
			InetAddress address = InetAddress.getByName(host);
			return address.getHostAddress();
		} catch (Exception e) {
			System.out.println("unknown host: " + host);
			e.printStackTrace();
			return "";
		}
	}

	public static String getDomain(String host) {
		if (host == null) {
			return "";
		}
		host = StringUtil.replace(host, "http://", "");
		int pnum = StringUtil.find(host, ".");
		if (pnum == 1 || pnum == 0) {
			return host;
		} else if (pnum == 2) {
			String[] lits = host.split("\\.");
			if (lits[1].length() == 3 && lits[2].length() == 2) {
				return host;
			}
			return host.substring(host.indexOf(".") + 1);
		} else if (pnum > 2) {
			String[] lits = host.split("\\.");
			if (lits[lits.length - 1].length() >= 3) {
				return lits[lits.length - 2] + "." + lits[lits.length - 1];
			} else if (lits[lits.length - 2].length() <= 3) {
				return lits[lits.length - 3] + "." + lits[lits.length - 2] + "." + lits[lits.length - 1];
			} else {
				return lits[lits.length - 2] + "." + lits[lits.length - 1];
			}
		}
		return host;
	}

	public static String getHost(String url) {
		if (!StringUtil.isFine(url)) {
			return "";
		}
		try {
			return new URL(url).getHost();
		} catch (Exception e) {
		}
		if (url.indexOf("://") == -1) {
			url = "http://" + url;
		}
		Pattern p = Pattern.compile("[^\\:]*\\:\\/\\/([^\\/]*)");
		for (Matcher m = p.matcher(url); m.find();) {
			return m.group(1);
		}
		return "";
	}

	/**
	 * ��Ե�ַת��Ϊ��Ե�ַ
	 * 
	 * @param fromurl
	 * @param url
	 * @return
	 */
	public static String getFullUrl(String fromurl, String url) {
		try {
			if (StringUtil.find(fromurl, "/") > 2) {
				fromurl = fromurl.substring(0, fromurl.lastIndexOf("/") + 1);
			} else {
				fromurl = fromurl + "/";
			}
			URI uri = new URI(fromurl);
			url = uri.resolve(new URI(url)).toString();
		} catch (Exception e) {
		}
		return url;
	}

	public static String getBaseHref(String url) {
		try {
			URI uri = new URI(url);
			String path = uri.getPath();
			return uri.getHost() + "/" + path.substring(0, path.lastIndexOf("/"));
		} catch (Exception e) {
			return "";
		}
	}

	public static long getLmodify(String url) {
		try {
			URL urlobj = new URL(url);
			URLConnection conn = urlobj.openConnection();
			return conn.getLastModified();
		} catch (Exception e) {
			return 0L;
		}
	}

	private static Pattern PwgetImgs = Pattern.compile("<img(.*?)src=([^ >]*)(.*?)>", Pattern.CASE_INSENSITIVE);

	public static String changeURL(String str, String url) {
		int slashs = StringUtil.find(url, "/");
		if (slashs < 2) {
			return str;
		} else if (slashs == 2) {
			url = url + "/";
		}
		try {
			StringBuffer sb = new StringBuffer();
			Matcher m = PwgetImgs.matcher(str);
			String theimg = "";
			while (m.find()) {
				theimg = m.group(2);
				theimg = StringUtil.replace(theimg, "\"", "");
				theimg = StringUtil.replace(theimg, "'", "");
				if (theimg.endsWith("/")) {
					theimg = theimg.substring(0, theimg.length() - 1);
				}
				m.appendReplacement(sb, "<img" + m.group(1) + "src=\"" + getFullUrl(url, theimg) + "\"" + m.group(3) + ">");
			}
			m.appendTail(sb);
			return sb.toString();
		} catch (Exception e) {
			return str;
		}
	}

	public static String encodeUrl(String url) {
		return encodeUrl(url, "GBK");
	}

	public static String encodeUrl(String url, String encoding) {
		if (!StringUtil.isFine(url)) {
			return url;
		}
		char[] cs = url.toCharArray();
		StringBuffer sb = new StringBuffer();
		try {
			for (int i = 0; i < cs.length; i++) {
				if (cs[i] > 255) {
					sb.append(URLEncoder.encode(String.valueOf(cs[i]), encoding));
				} else {
					sb.append(cs[i]);
				}
			}
			return sb.toString();
		} catch (Exception e) {
			return url;
		}
	}
}
